﻿using System;
using System.Linq;
using Csla;
using BizControl.DalLinq;
using BizControl.Library.BusinessObjects.Activities;
using BizControl.Library.BusinessObjects.Models;
using BizControl.Resources;

namespace BizControl.Library.BusinessObjects.People
{
  public class PersonModelActivities : BusinessListBase<PersonModelActivities, ActivityBO>
  {
    #region  Business Methods

    private PersonBO Person;
    private ModelBO Model;

    public ActivityBO this[ActivityBO activitySearchFor]
    {
      get
      {
        foreach (ActivityBO activity in this)
        {
          if (activity.ActivityId == activitySearchFor.ActivityId)
            return activity;
        }
        return null;
      }
    }

    public ActivityBO AddActivity()
    {
      var activity = ActivityBO.NewActivity(Person, Model);
      this.Add(activity);
      return activity;
    }

    public void Remove(Guid activityId)
    {
      foreach (ActivityBO activity in this)
      {
        if (activity.ActivityId == activityId)
        {
          Remove(activity);
          break;
        }
      }
    }

    public bool Contains(Guid activityId)
    {
      foreach (ActivityBO activity in this)
        if (activity.ActivityId == activityId)
          return true;
      return false;
    }

    public bool ContainsDeleted(Guid activityId)
    {
      foreach (ActivityBO activity in DeletedList)
        if (activity.ActivityId ==  activityId)
          return true;
      return false;
    }

    #endregion

    #region Factory Methods

    internal static PersonModelActivities NewPersonModelActivities(PersonBO person, ModelBO model)
    {
      return DataPortal.CreateChild<PersonModelActivities>(person, model);
    }

    internal static PersonModelActivities GetPersonModelActivities(Activity[] data, PersonBO person, ModelBO model)
    {
      return DataPortal.FetchChild<PersonModelActivities>(data, person, model);
    }

    private PersonModelActivities()
    { /* require use of factory methods */ }

    #endregion

    #region  Data Access

    private void Child_Fetch(Activity[] data, PersonBO person, ModelBO model)
    {
      if (model == null) throw new ArgumentNullException(ExceptionsMessages.ModelNullReference);
      if (person == null) throw new ArgumentNullException(ExceptionsMessages.PersonNullReference);
      Person = person;
      Model = model;
      if (data == null) return;
      this.RaiseListChangedEvents = false;
      foreach (var child in data)
        Add(ActivityBO.GetActivity(child.ActivityId));
      this.RaiseListChangedEvents = true;
    }

    #endregion

  }
}
